export class CountdownTimer {
  constructor({ selector, targetTime, onComplete }) {
    this.selector = selector;
    this.targetTime = targetTime;
    this.onComplete = onComplete || function () { };
    this.animationFrameId = null;
    this.isRunning = false;

    this.daysEl = document.querySelector(`${selector} .days`);
    this.hoursEl = document.querySelector(`${selector} .hours`);
    this.minutesEl = document.querySelector(`${selector} .minutes`);
    this.secondsEl = document.querySelector(`${selector} .seconds`);
    this.millisecondsEl = document.querySelector(`${selector} .milliseconds`);

    this.start = this.start.bind(this);
    this.stop = this.stop.bind(this);
    this.update = this.update.bind(this);
  }

  start() {
    if (this.isRunning) return;

    this.isRunning = true;
    this.startTime = Date.now();
    this.remainingTime = this.targetTime - this.startTime;

    this.lastTime = this.startTime;
    this.animationFrameId = requestAnimationFrame(this.update);
  }

  stop() {
    if (!this.isRunning) return;

    cancelAnimationFrame(this.animationFrameId);
    this.isRunning = false;
  }

  update(currentTime) {
    if (!this.isRunning) return;

    // 计算剩余时间（毫秒）
    const elapsed = currentTime - this.lastTime;
    this.lastTime = currentTime;
    this.remainingTime -= elapsed;
    // console.log(this.remainingTime);


    // 如果倒计时结束
    if (this.remainingTime <= 0) {
      this.remainingTime = 0;
      this.stop();
      this.onComplete();
    }

    // 更新时间显示
    this.updateDisplay(this.remainingTime);

    // 继续动画循环
    this.animationFrameId = requestAnimationFrame(this.update);
  }

  updateDisplay(ms) {
    // 计算各个时间单位
    const totalSeconds = ms / 1000;
    const minutes = Math.floor(totalSeconds / 60) % 60;
    const seconds = Math.floor(totalSeconds % 60);
    const milliseconds = Math.floor((ms % 1000) / 10); // 显示2位毫秒

    // 更新DOM
    if (this.minutesEl) this.minutesEl.textContent = this.formatTime(minutes);
    if (this.secondsEl) this.secondsEl.textContent = this.formatTime(seconds);
    if (this.millisecondsEl) this.millisecondsEl.textContent = this.formatTime(milliseconds, true);
  }

  formatTime(value, isMilliseconds = false) {
    if (isMilliseconds) {
      return value < 10 ? `0${value}` : value;
    }
    return value < 10 ? `0${value}` : value;
  }
}
